package com.cmy.framework_network.apiresponse

import com.cmy.framework_network.base.Envelope
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.rawType
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class MoshiResultTypeAdapterFactory(private val envelope: Envelope?) : JsonAdapter.Factory{
    override fun create(
        type: Type,
        annotations: MutableSet<out Annotation>,
        moshi: Moshi
    ): JsonAdapter<*>? {
        val rawType = type.rawType
        if (rawType != NetworkResponse::class.java) return null
        val dataType: Type =
            (type as? ParameterizedType)?.actualTypeArguments?.firstOrNull() ?: return null
        val dataTypeAdapter = moshi.nextAdapter<Any>(this, dataType, annotations)
        return ResultTypeAdapter(dataTypeAdapter, envelope)
    }
}

